// collab-manage-system/ent/schema/activityparticipant.go
package schema

import (
	"time"

	"entgo.io/ent"
	"entgo.io/ent/dialect/entsql"
	"entgo.io/ent/schema"
	"entgo.io/ent/schema/edge"
	"entgo.io/ent/schema/field"
	"entgo.io/ent/schema/index"
)

// ActivityParticipant 活动参与者
type ActivityParticipant struct {
	ent.Schema
}

// Fields 活动参与者字段
func (ActivityParticipant) Fields() []ent.Field {
	return []ent.Field{
		field.Int64("id").
			Positive().
			Unique().
			Immutable(),
		// 显式定义外键字段
		field.Int64("activity_id").
			StorageKey("activity_id").
			Comment("活动ID"),
		field.Int64("user_id").
			StorageKey("user_id").
			Comment("用户ID"),
		field.Int64("department_id").
			Optional().
			Nillable().
			StorageKey("department_id").
			Comment("部门ID"),
		field.Enum("status").
			Values("invited", "confirmed", "declined", "attended").
			Default("invited").
			Comment("参与状态"),
		field.Time("created_at").
			Default(time.Now).
			Immutable(),
	}
}

// Edges 活动参与者关联
func (ActivityParticipant) Edges() []ent.Edge {
	return []ent.Edge{
		// activity_id 字段不是 Optional().Nillable()，所以边需要 Required()
		edge.From("activity", Activity.Type).
			Ref("participants").
			Field("activity_id").
			Unique().
			Required(). // 添加 Required()
			Comment("所属活动"),
		// user_id 字段不是 Optional().Nillable()，所以边需要 Required()
		edge.From("user", User.Type).
			Ref("activity_participations").
			Field("user_id").
			// 注意：这里不加 Unique()，因为一个用户可以参与多个活动，但一个参与记录只对应一个用户
			Required(). // 添加 Required()
			Unique().   // 添加 Unique
			Comment("参与用户"),
		// department_id 字段是 Optional().Nillable()，所以边 *不能* 加 Required()
		edge.From("department", Department.Type).
			Ref("activity_participations").
			Field("department_id").
			Unique().
			Comment("参与部门"),
	}
}

// Indexes 索引
func (ActivityParticipant) Indexes() []ent.Index {
	return []ent.Index{
		// 确保同一用户不会多次参加同一活动
		index.Fields("activity_id", "user_id").
			Unique(),
		index.Fields("user_id"),
		index.Fields("department_id"),
	}
}

// Annotations of the ConversationMember.
func (ActivityParticipant) Annotations() []schema.Annotation {
	return []schema.Annotation{
		entsql.Annotation{
			Table: "act_participants",
		},
	}
}
